﻿#region

using System;
using System.Collections.Generic;
using System.Reflection;
using Lab.DataContext.DataContext;

#endregion

namespace Lab.Tests.ApplicationTest {
    public class DataContextFake : IDataContext {
        private static int increment = 1;

        private readonly Dictionary<Type, List<KeyValuePair<int, object>>> entities =
            new Dictionary<Type, List<KeyValuePair<int, object>>>();

        public void InsertInTable<TDataObject>(TDataObject dataObject) where TDataObject : class {
            if (entities.ContainsKey(typeof (TDataObject))) {
                entities[typeof (TDataObject)].Add(new KeyValuePair<int, object>(increment++, dataObject));
            }
            else {
                var pair = new KeyValuePair<int, object>(increment++, dataObject);
                entities.Add(typeof (TDataObject), new List<KeyValuePair<int, object>> { pair });
            }
        }

        public List<skill> GetSkills() {
            return GetListOf<skill>();
        }

        public List<kind_of_activity> GetKindOfActivities() {
            return GetListOf<kind_of_activity>();
        }

        public List<employer> GetEmployers() {
            return GetListOf<employer>();
        }

        public List<applicant> GetApplicants() {
            return GetListOf<applicant>();
        }

        public List<vacancy> GetVacancies() {
            return GetListOf<vacancy>();
        }

        public List<deal> GetDeals() {
            return GetListOf<deal>();
        }

        public void SubmitChanges() {}

        private List<T> GetListOf<T>() {
            var keyValuePairs = entities[typeof (T)];
            var skills = keyValuePairs.ConvertAll(ConvertTo<T>);
            return skills;
        }

        private static T ConvertTo<T>(KeyValuePair<int, object> keyValuePair) {
            var value = (T) keyValuePair.Value;
            SetId(keyValuePair, value);
            
            return value;
        }

        private static void SetId<T>(KeyValuePair<int, object> keyValuePair, T value) {
            var idName = string.Format("{0}_id", typeof (T).Name);
            var prop = value.GetType().GetProperty(idName, BindingFlags.Public | BindingFlags.Instance);
            if (null != prop && prop.CanWrite) {
                prop.SetValue(value, keyValuePair.Key);
            }
        }
    }
}